import re
import pypinyin


def case_to_underline(text):
    lst = []
    for index, char in enumerate(text):
        if char.isupper() and index != 0:
            lst.append('_')
        lst.append(char)
    return ''.join(lst).lower()


def pinyin(word):
    s = ''
    word_pinyin = ''
    for pinyin in pypinyin.pinyin(word, style=pypinyin.NORMAL):
        word_pinyin += ''.join(py for py in pinyin)
    for index, i in enumerate(word_pinyin):
        if index == 0:
            s += ''.join(i).upper()
        else:
            s += ''.join(i)
    return s


def trim_district_name(name):
    if len(name) > 2:
        r1 = r'(自治区)|(自治州)|(特别行政区)|(地区)'
        r2 = r'(省)|(市)|(区)|(县)|(州)'
        r3 = r'(汉族)|(蒙古族)|(回族)|(藏族)|(维吾尔族)|(维吾尔)|(苗族)|(彝族)|(壮族)|(布依族)|(朝鲜族)|(满族)|(侗族)|(瑶族)|(白族)|' \
             r'(土家族)|(哈尼族)|(哈萨克族)|(傣族)|(黎族)|(傈僳族)|(佤族)|(畲族)|(高山族)|(拉祜族)|(水族)|(东乡族)|(纳西族)|' \
             r'(景颇族)|(柯尔克孜族)|(土族)|(达斡尔族)|(仫佬族)|(羌族)|(布朗族)|(撒拉族)|(毛难族)|(仡佬族)|(锡伯族)|(阿昌族)|' \
             r'(普米族)|(塔吉克族)|(怒族)|(乌孜别克族)|(俄罗斯族)|(鄂温克族)|(崩龙族)|(保安族)|(裕固族)|(京族)|(塔塔尔族)|' \
             r'(独龙族)|(鄂伦春族)|(赫哲族)|(门巴族)|(珞巴族)|(基诺族)'

        r_list = [r1, r3]
        for r in r_list:
            pattern = re.compile(r, re.MULTILINE | re.DOTALL)
            dest = pattern.findall(name)
            # 有匹配到
            if len(dest) != 0:
                de = dest[0]
                for d in de:
                    if d != '':
                        name = name.replace(d, '')
        # r'省|市|区|县|州'，像福州市、达州市、郑州市这种，避免把中间的州字去掉
        pattern = re.compile(r2, re.MULTILINE | re.DOTALL)
        dest = pattern.findall(name)
        if len(dest) != 0:
            for de in dest:
                for d in de:
                    # 匹配到的是最后一个字才替换
                    if d != '' and name[-1] == d:
                        name = name.replace(d, '')
    names = {'name': name, 'pinyin': pinyin(name)}
    return names


if __name__ == '__main__':
    print(trim_district_name('喀什地区'))
